//
//  BKPhone_NumberView.m
//  bestkeep
//
//  Created by yons on 16/11/25.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKPhone_NumberView.h"
#import <Masonry.h>
#import "BKMainCommon.h"
#import "BKContactPeople.h"


#define MARGIN 10

@implementation BKPhone_NumberView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = RGBACOLOR(242, 242, 242, 1);
        [self initViews];
    }
    return self;
}

- (void)initViews{
    UIView *whiteView = [[UIView alloc]init];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self addSubview:whiteView];
    [whiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left);
        make.right.mas_equalTo(self.mas_right);
        make.top.mas_equalTo(self.mas_top).offset(10);
        make.bottom.mas_equalTo(self.mas_bottom).offset(-10);
    }];
    
    _contactImageView = [[UIImageView alloc]init];
    _contactImageView.userInteractionEnabled = YES;
    _contactImageView.image = [UIImage imageNamed:@"BKPhone_TXbutton"];
    UITapGestureRecognizer *selectContactTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectContact)];
    [_contactImageView addGestureRecognizer:selectContactTap];
    [whiteView addSubview:_contactImageView];
    [_contactImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.mas_right).offset(-17);
        make.top.mas_equalTo(whiteView.mas_top).offset(20);
        make.width.mas_equalTo(22);
        make.height.mas_equalTo(22.5);
 
    }];
    
    _phoneTextField = [[UITextField alloc]init];
    _phoneTextField.textColor = [UIColor blackColor];
    _phoneTextField.font = [UIFont systemFontOfSize:30];
    [_phoneTextField setPlaceholder:@"请输入充值手机号"];
    [_phoneTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [_phoneTextField addTarget:self action:@selector(textValueChanged:) forControlEvents:UIControlEventEditingChanged];
    [_phoneTextField addTarget:self action:@selector(textFieldWillEditing:) forControlEvents:UIControlEventEditingDidBegin];
    [_phoneTextField addTarget:self action:@selector(textFieldDidEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
    [_phoneTextField setKeyboardType:UIKeyboardTypePhonePad];
    
    UIView *accessoryView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    accessoryView.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1.0];
    UIButton *cancleButton = [[UIButton alloc] initWithFrame:CGRectMake(MARGIN, MARGIN, 50, 20)];
    
    [cancleButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancleButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    UIButton *cancleBigButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth/2-20, 40)];
    [cancleBigButton addTarget: self action:@selector(cancleKeyBoardAction:) forControlEvents:UIControlEventTouchUpInside];
    [accessoryView addSubview:cancleButton];
    [accessoryView addSubview:cancleBigButton];
    UIButton *finishButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth - 6 * MARGIN, MARGIN, 50, 20)];
    [finishButton setTitle:@"完成" forState:UIControlStateNormal];
    [finishButton setTitleColor:RGBACOLOR(136, 136, 136, 1) forState:UIControlStateNormal];
    [finishButton setTintColor:[UIColor redColor]];
    UIButton *finishBigButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth/2+20, 0, ScreenWidth/2-20, 40)];
    [finishBigButton addTarget:self action:@selector(finishKeyBoardAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [accessoryView addSubview:finishButton];
    [accessoryView addSubview:finishBigButton];
    self.phoneTextField.inputAccessoryView = accessoryView;
    [whiteView addSubview:_phoneTextField];
    [_phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left).offset(17);
        make.top.mas_equalTo(self.mas_top).offset(20);
        make.right.mas_equalTo(self.contactImageView.mas_left).offset(-10);
        make.bottom.mas_equalTo(self.mas_bottom).offset(-32);
    }];
    
    _QCellCoreLabel = [[UILabel alloc]init];
    _QCellCoreLabel.font = [Common systemFontOfSize:12];
    _QCellCoreLabel.textColor = HexColor(0x888888);
    [whiteView addSubview:_QCellCoreLabel];
    [_QCellCoreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left).offset(17);
        make.top.mas_equalTo(self.phoneTextField.mas_bottom).offset(0);
        make.right.mas_equalTo(self.mas_right).offset(-10);
        make.height.mas_equalTo(12);
    }];
}
//选取联系人电话
-(void)selectContact{
   
    int __block tip = 0;
    ABAddressBookRef addBook = nil;
    if ([[UIDevice currentDevice].systemVersion floatValue]>6.0) {
        
        addBook = ABAddressBookCreateWithOptions(NULL, NULL);
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addBook, ^(bool granted, CFErrorRef error) {
            if (!granted) {
                tip = 1;
            }
            
            dispatch_semaphore_signal(sema);
            
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }else{
        //IOS6之前
        addBook =ABAddressBookCreate();
    }
    if (tip) {
        //做一个友好的提示
        UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请您设置允许BestKeep访问您的通讯录\n前往设置>隐私>通讯录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alart show];
        
    }
    else{
        __weak typeof(self)wSelf = self;
        if ([self.delegate respondsToSelector:@selector(addContactPerson:chooseContactPeople:)]) {
            [self.delegate addContactPerson:self chooseContactPeople:^(ABRecordRef person, NSString *phoneNumber) {
                {
                    BKContactPeople * people = [[BKContactPeople alloc] init];
                    [people getPersonAddressBookToPhoneCards:person];
                    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\"- "];
                    NSString *telephone;
                    if (phoneNumber.length) {
                        telephone = [[phoneNumber componentsSeparatedByCharactersInSet:set]componentsJoinedByString:@""];
                    }else {
                        telephone =[[people.telephone componentsSeparatedByCharactersInSet:set]componentsJoinedByString:@""];
                    }
                    wSelf.phoneTextField.text = [self formattingPhoneNumber:telephone];
                    if (telephone.length != 11) {
                        wSelf.QCellCoreLabel.text = @"手机号码格式错误";
                    }else {
                        wSelf.QCellCoreLabel.text = people.name;
                    }
                    [self endInput];
                }
            }];

        }
    }
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    switch (buttonIndex) {
        case 0:
            
            [self gotoBeetKeepSeting];
            break;
            
        case 1:
            
            break;
            
        default:
            break;
    }
}
- (void)gotoBeetKeepSeting {
    
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)textValueChanged:(UITextField *)textField {
    if ([self.PhoneNumberdelegate respondsToSelector:@selector(phoneCardsNumberView:textValueChanged:)]) {
        textField.text = [self formattingPhoneNumber:textField.text];
        [self.PhoneNumberdelegate phoneCardsNumberView:self textValueChanged:textField];
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    if ([self.PhoneNumberdelegate respondsToSelector:@selector(phoneCardsNumberView:textFieldShouldEndEditing:)]) {
        
        [self.PhoneNumberdelegate phoneCardsNumberView:self textFieldShouldEndEditing:textField];
    }
}
- (void)textFieldWillEditing:(UITextField *)textField {
    
    if ([self.PhoneNumberdelegate respondsToSelector:@selector(phoneCardsNumberView:textFieldShouldBeginEditing:)]) {
        
        [self.PhoneNumberdelegate phoneCardsNumberView:self textFieldShouldBeginEditing:textField];
    }
}

- (void)endInput {
    if ([self.delegate respondsToSelector:@selector(updateDataFromServerPhoneNumber: numberInfo:)]) {
        [self.delegate updateDataFromServerPhoneNumber:[self.phoneTextField.text stringByReplacingOccurrencesOfString:@"  " withString:@""] numberInfo:self.QCellCoreLabel.text];
    }
}

//标准化 电话号码 111 1111 1111
- (NSString *)formattingPhoneNumber:(NSString *)text {
    
    NSMutableString *mutStr = [text mutableCopy];
    
    if (mutStr.length) {
        
        NSString *passwordStandard = @"^[0-9]+$";
        NSRegularExpression *regexpasswordStandard = [NSRegularExpression regularExpressionWithPattern:passwordStandard options:0 error:nil];
        
        NSTextCheckingResult *isMatchpasswordStandard = [regexpasswordStandard firstMatchInString:mutStr options:0 range:NSMakeRange(mutStr.length-1, 1)];
        
        if (isMatchpasswordStandard) { //符合要求
            
            if ([[text substringWithRange:NSMakeRange(mutStr.length-1, 1)] isEqualToString:@" "]) {
                [mutStr deleteCharactersInRange:NSMakeRange(mutStr.length-1, 1)];
            }else {
                if (text.length > 3 && ![[text substringWithRange:NSMakeRange(3, 1)] isEqualToString:@" "]) {
                    [mutStr insertString:@" " atIndex:3];
                }
                if (text.length > 8 && ![[text substringWithRange:NSMakeRange(8, 1)] isEqualToString:@" "]) {
                    [mutStr insertString:@" " atIndex:8];
                }
            }
            
            text = mutStr;
            
        }else {
            text = [text substringToIndex:mutStr.length - 1];
        }
    }
    return text;
}

- (void)cancleKeyBoardAction:(UIButton *)sender {
    
    if ([self.delegate respondsToSelector:@selector(cancleKeyBoardAction:)]) {
        [self.delegate cancleKeyBoardAction:sender];
    }
}

- (void)finishKeyBoardAction:(UIButton *)sender {
    
    if ([self.delegate respondsToSelector:@selector(finishKeyBoardAction:)]) {
        [self.delegate finishKeyBoardAction:sender];
    }
}

@end
